package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"time"
)

type CourseService interface {
	Create(req *model.CourseCreateReq) error
	Update(id uint, req *model.CourseUpdateReq) error
	Delete(id uint) error
	GetByID(id uint) (*model.Course, error)
	List(page, pageSize int) ([]model.Course, int64, error)
}

type courseService struct {
	repo repository.CourseRepository
}

func NewCourseService(repo repository.CourseRepository) CourseService {
	return &courseService{repo: repo}
}

func (s *courseService) Create(req *model.CourseCreateReq) error {
	startTime, err := time.Parse("2006-01-02 15:04:05", req.StartTime)
	if err != nil {
		return errors.New("开始时间格式错误")
	}

	endTime, err := time.Parse("2006-01-02 15:04:05", req.EndTime)
	if err != nil {
		return errors.New("结束时间格式错误")
	}

	course := &model.Course{
		Name:        req.Name,
		Description: req.Description,
		CoachID:     req.CoachID,
		MaxCapacity: req.MaxCapacity,
		Duration:    req.Duration,
		StartTime:   startTime,
		EndTime:     endTime,
		Status:      1,
	}

	return s.repo.Create(course)
}

func (s *courseService) Update(id uint, req *model.CourseUpdateReq) error {
	course, err := s.repo.GetByID(id)
	if err != nil {
		return errors.New("课程不存在")
	}

	if req.Name != "" {
		course.Name = req.Name
	}
	if req.Description != "" {
		course.Description = req.Description
	}
	if req.CoachID != nil {
		course.CoachID = *req.CoachID
	}
	if req.MaxCapacity != nil {
		course.MaxCapacity = *req.MaxCapacity
	}
	if req.Duration != nil {
		course.Duration = *req.Duration
	}
	if req.Status != nil {
		course.Status = *req.Status
	}
	if req.StartTime != "" {
		if t, err := time.Parse("2006-01-02 15:04:05", req.StartTime); err == nil {
			course.StartTime = t
		}
	}
	if req.EndTime != "" {
		if t, err := time.Parse("2006-01-02 15:04:05", req.EndTime); err == nil {
			course.EndTime = t
		}
	}

	return s.repo.Update(course)
}

func (s *courseService) Delete(id uint) error {
	if _, err := s.repo.GetByID(id); err != nil {
		return errors.New("课程不存在")
	}
	return s.repo.Delete(id)
}

func (s *courseService) GetByID(id uint) (*model.Course, error) {
	return s.repo.GetByID(id)
}

func (s *courseService) List(page, pageSize int) ([]model.Course, int64, error) {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return s.repo.List(page, pageSize)
}
